import { reactive, watch } from 'vue'

import { getMetaDataState } from './state/state-meta-data'

// 定义列表需要的 meta
const gridMeta = reactive({
  gridMeta: {
    moduleId: 142,
    idName: 'ID',
    colOrder: []
  },
  height: 400,
  stripe: true,
  border: true,
  fit: true,
  'highlight-current-row': true,
  itemMeta: {}
})

// 字段单独的meta
const itemMeta = reactive({})

// 模拟数据
const createData = (cols, i) => {
  const list = {}

  cols.forEach((col, index) => {
    list[col.colName] = col.cnName + '_' + i
  })

  return list
}

/**
 * 创建字段的 meta
 */
export const toMetaGrid = () => {
  const state = getMetaDataState()
  // const { sheetNames, current } = state

  const dataList = reactive([]) //_dataList

  const _toMetaCol = (cols) => {
    // 清空
    dataList.length = 0
    for (let i = 0; i < 5; i++) {
      dataList.push(createData(cols, i))
    }

    for(const key in itemMeta) {
      delete itemMeta[key]
      delete gridMeta.gridMeta[key]
    }
    gridMeta.gridMeta.colOrder.length = 0

    gridMeta.gridMeta.idName = cols[0].colName

    // 遍历
    cols.forEach((col, index) => {
      const meta = {
        id: col.columnId,
        colName: col.colName,
        label: col.cnName,
        width: 140,
        title: col.cnName,
        align: 'center',
        'header-align': 'center'
      }
      itemMeta[col.columnId] = meta
      gridMeta.itemMeta[col.columnId] = meta
      gridMeta.gridMeta.colOrder.push(col.columnId)
    })
  }

  watch(state.current.table.cols, (cols) => {
    // clearTimeout(state.timeoutGrid)
    // state.timeoutGrid = setTimeout(() => {
      _toMetaCol(cols)
      console.log('创建一次列表meta')
    // }, 100)
    
  })

  return {
    dataList,
    gridMeta,
    itemMeta
  }
}